const oracleManager = require('../manager/oracleManager');
const schedule = require('node-schedule');
const { formatDate } = require('./util');
const { Date_Format } = require('./constant');
const redisManager = require('../manager/redisManager');
// const oracleManager = require('../manager/oracleManager');
const logHandler = require('../component/logHandler');
const RedisConfig = require('../config/RedisConfig');

/**
 * 启动定时任务。将ADAM库中的mdl_stock_analysis表中的数据加载到redis
 */
exports.loadMdlStockAnalysisIntoRedis = (date) => {
  let rule = new schedule.RecurrenceRule();
  // const times = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56];
  const times = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29,
    31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59];
  // 每个小时执行一次
  // const times = [0];
  rule.minute = times;
  schedule.scheduleJob(rule, async () => {
    logHandler.info('启动定时任务。将ADAM库中的mdl_stock_analysis表中的数据加载到redis');

    // 从oracle数据库的mdl_stock_analysis表中查找date_字段最大值
    let maxDate = await oracleManager.findMaxDateOfMdlStockAnalysis();
    let maxDateString = formatDate(maxDate, Date_Format.YYYY_MM_DD);

    // 以最大日期为key，查找redis中是否有对应的数据
    let mdlStockAnalysisMap = await redisManager.hgetall(maxDateString).then((result) => {
      return result;
    }, (err) => {
      logHandler.error(err);
      return null;
    });

    if(!mdlStockAnalysisMap){
      // 如果在redis中没有找到对应的数据，则从oracle中，根据最大日期，返回mdl_stock_analysis表中的记录
      let mdlStockAnalysisList = await oracleManager.findMdlStockAnalysisByDate(date).then((result) => {
        return result;
      }, (err) => {
        logHandler.error(err);
        return null;
      });
    
      // 如果mdl_stock_analysis表中有日期为maxDateString的数据，则将其存储在redis中
      if(mdlStockAnalysisList){
        logHandler.info(`mdl_stock_analysis表中有日期为${maxDateString}的数据，开始将其存储在redis中`);

        // 向redis中存储最大日期
        await redisManager.set(RedisConfig.KEY_OF_MAX_DATE_OF_MDL_STOCK_ANALYSIS_IN_REDIS, maxDateString);
        // 向redis存储mdl_stock_analysis数据
        for(let i=0; i<mdlStockAnalysisList.length; i++){
          let mdlStockAnalysis = mdlStockAnalysisList[i];
          await redisManager.hset(maxDateString, mdlStockAnalysis.CODE_, JSON.stringify(mdlStockAnalysis), RedisConfig.MDL_STOCK_ANALYSIS_DEFAULT_EXPIRE_TIME);
        }
      } else {
        logHandler.info(`mdl_stock_analysis表中没有日期为${maxDateString}的数据`);
      }
    } else {
      logHandler.info(`redis中已有日期为${maxDateString}的数据`);
    }
  })
};


